from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from goods.models import SKUImage, SKU
from meiduo_admin.my_paginate import MyPageNumberPagination
from meiduo_admin.sku import sku_images_serializers


class SKUImagesViewSet(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = sku_images_serializers.SKUImagesSerializer
    queryset = SKUImage.objects.all()

    # 1，获取所有的sku的信息
    def simple(self,request):

        # 获取所有的sku对象
        skus = SKU.objects.all()
        # 获取序列化器
        serializer = sku_images_serializers.SKUSimpleSerializer(instance=skus,many=True)
        #返回响应
        return Response(serializer.data)

    # 重写create方法，实现图片的上传保存
    def create(self, request, *args, **kwargs):
        #1,获取参数
        image =request.FILES.get("image")
        sku_id = request.data.get("sku")
        #2，校验参数
        if not all([image,sku_id]):
            return Response(status=403)
        #3，数据入库
        client = Fdfs_client(settings.FDFS_CONFIG) # 创建fdfs对象
        ret = client.upload_by_buffer(image.read()) # 上传图片，二进制方法，转二进制上传
        #3.1 判断是否成功
        if ret["Status"] != "Upload successed.":
            return Response(status=400)
        #3.2 数据入库图片
        image_url =ret.get("Remote file_id") # 从ret中取出远程的文件id
        SKUImage.objects.create(sku_id=sku_id,image=image_url)
        #4，返回响应
        return Response(status=201)

    # 重写update方法，修改图片
    def update(self, request, *args, **kwargs):
        #1,获取参数
        image = request.FILES.get("image")
        sku_id = request.data.get("sku")
        sku_image = self.get_object() # 通过pk去取？什么鬼

        #2，校验参数
        if not all([image,sku_id]):
            return Response(status=403)
        #3，数据入库
        client = Fdfs_client(settings.FDFS_CONFIG)
        ret = client.upload_by_buffer(image.read())

        #3.1.判断是否成功
        if ret["Status"] != "Upload successed":
            return Response(status=400)
        #3.2，数据入库图片
        image_url = ret.get("Remote file_id")
        SKUImage.objects.filter(id=sku_image.id).update(sku_id=sku_id,image=image_url)
        #4,返回响应
        return Response(status=201)


